from flask import Flask, request, jsonify, send_from_directory
import mysql.connector
from werkzeug.security import check_password_hash
from flask_cors import CORS
from flask import session
from langchain_02_models import bl

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 配置MySQL连接
config = {
    'user': 'myuser',
    'password': '123456',
    'host': '127.0.0.1',
    'port': '3306',
    'database': 'dbsclab2018'
}

app.secret_key = '123456'
@app.route('/')
def index():
    return send_from_directory('static', 'denglu.html')

@app.route('/api/login', methods=['POST'])
def login():
    # 获取前端发送的数据
    username = request.json.get('username')
    bl.set_us(username)
    print (bl.us)
    password = request.json.get('password')
    # session['CURRENT_USERNAME'] = username
    if not username or not password:
        return jsonify({'success': False, 'message': '用户名和密码不能为空'}), 400

    # 创建数据库连接
    db_connection = mysql.connector.connect(**config)
    cursor = db_connection.cursor()

    try:
        # 检查用户名是否存在
        cursor.execute("SELECT password FROM users WHERE username = %s", (username,))
        user = cursor.fetchone()

        if user:
            stored_password_hash = user[0]
            # 验证密码

            if check_password_hash(stored_password_hash, password):
                # app.config['CURRENT_USERNAME'] = username  # 存储用户名到 Flask 配置
                # 登录成功
                session['CURRENT_USERNAME'] = username  # 存储用户名到 session

                # print(bl.us)
                return jsonify({'success': True, 'message': '登录成功'}), 200
            else:
                # 密码错误
                return jsonify({'success': False, 'message': '密码错误'}), 401
        else:
            # 用户名不存在
            return jsonify({'success': False, 'message': '用户名不存在'}), 404
    finally:
        cursor.close()
        db_connection.close()

print(bl.us)
if __name__ == '__main__':
    app.run(debug=True, port=2000)